﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using DotNet.Utilities;

namespace TextApiHelper
{
    public partial class FormMain : Form
    {
        /// <summary>
        /// 类型替换字典
        /// </summary>
        readonly Dictionary<string, string> _TypeReplaceDict = new Dictionary<string, string>()
        {
            { "date", "DateTime" }, { "datetime", "DateTime" }, { "String", "string" }, {"json", "JObject"}, { "JSON", "JObject" }, { "jsonArray", "List<object>" },
            { "string[]", "List<string>" }, { "bigdecimal", "decimal" }, { "id", "int" }, { "boolean", "bool" }, { "Double", "double" }, { "Int", "int" },
        };

        /// <summary>
        /// 可为空类型;
        /// </summary>
        readonly List<string> _WillBeNullTypes = new List<string>() { "DateTime", "bool", "decimal", "int" };

        public FormMain()
        {
            InitializeComponent();

            Text += $" 版本[{AssemblyHelper.AssemblyVersion}]";
        }

        /// <summary>
        /// 方案一：0.字段名、1.变量名、2.是否必填、3.类型、4.示例值、5.描述
        /// </summary>
        private void Button1_Click(object sender, EventArgs e)
        {
            var strs = TBContent.Text.Replace("\r\n", "\r").Split('\r');
            StringBuilder sb = new StringBuilder();
            bool hasName = false;

            sb.AppendLine("public class MyClass {");

            foreach (var str in strs)
            {
                if (string.IsNullOrEmpty(str))
                    continue;

                var ps = str.Split('\t');

                if (ps[0] == "字段名")
                    continue;

                if (ps.Length == 1)
                {
                    //sb.Append($"\r\n public {str} {str} {{get;set;}}");
                    if (hasName)
                    {
                        sb.Append($"{Environment.NewLine} }}\r\n");
                    }

                    sb.Append($@"
                    public class {str}{Environment.NewLine} {{");
                    hasName = true;
                }
                else
                {
                    string type = ps[3];
                    if (_WillBeNullTypes.Contains(type) && CBIsNullable.Checked)
                    {
                        type += "?";
                    }

                    sb.AppendLine($@"
                    /// <summary>
                    /// {ps[0]} {ps[2]} {(ps.Length > 5 ? ps[5] : "")} {(ps.Length > 4 ? ps[4] : "")}
                    /// </summary>
                    public {type} {ps[1]} {{get;set;}}");
                }
            }

            if (hasName)
            {
                sb.AppendLine("}");
            }

            sb.Append("}");

            TBResult.Text = sb.ToString();
            try
            {
                Clipboard.SetText(sb.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            //TBContent.Text = "";
        }

        /// <summary>
        /// 方案二：0.参数名、1.是否必须、2.类型、3.说明
        /// </summary>
        private void Button2_Click(object sender, EventArgs e)
        {
            var strs = TBContent.Text.Replace("\r\n", "\r").Split('\r');
            StringBuilder sb = new StringBuilder();
            List<string> needRemoveList = new List<string>() { "\r\n", " ", };

            sb.AppendLine($"public class MyClass {Environment.NewLine}{{");

            foreach (var str in strs)
            {
                if (string.IsNullOrEmpty(str))
                    continue;

                var ps = str.Split('\t');

                string propName = ps[0];
                if (propName == "参数名")
                {
                    continue;
                }

                foreach (string s in needRemoveList)
                {
                    propName = propName.Replace(s, "");
                }

                string type = ps[2];
                if (_TypeReplaceDict.ContainsKey(type))
                {
                    type = _TypeReplaceDict[type];
                }

                if (_WillBeNullTypes.Contains(type) && CBIsNullable.Checked)
                {
                    type += "?";
                }

                sb.AppendLine($@"
                    /// <summary>
                    /// [{ps[1]}] {(ps.Length > 3 ? ps[3] : "")}
                    /// </summary>
                    public {type} {ps[0]} {{get;set;}}");
            }

            sb.Append("}");

            TBResult.Text = sb.ToString();
        }

        /// <summary>
        /// 方案三：0.父节点、1.参数名、2.类型、3.说明
        /// </summary>
        private void Button3_Click(object sender, EventArgs e)
        {
            var strs = TBContent.Text.Replace("\r\n", "\r").Split('\r');
            StringBuilder sb = new StringBuilder();
            List<string> willBeNullTypes = new List<string>() { "DateTime", "bool", "decimal", "int" };
            string parentClass = string.Empty;

            sb.AppendLine($"public class MyClass {Environment.NewLine}{{");

            foreach (var str in strs.OrderBy(x => x.Split('\t')[0]))
            {
                if (string.IsNullOrEmpty(str))
                    continue;

                var ps = str.Split('\t');
                if (ps.Length == 3 || (new List<string> { "是", "否" }).Contains(ps[1]))
                {
                    ps = $"\t{str}".Split('\t');
                }

                //返回中多了“是否必须”列;
                if (ps.Length == 5)
                {
                    ps[2] = ps[3];
                    ps[3] = ps[4];
                }

                if (ps[0] == "父节点")
                    continue;

                if (ps[0] != parentClass)
                {
                    sb.Append($"{Environment.NewLine}\t}} \r\n\r\n");
                    sb.AppendLine($"\tpublic class {CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ps[0])} {Environment.NewLine}\t{{");
                    parentClass = ps[0];
                }

                string type = ps[2];
                if (_TypeReplaceDict.ContainsKey(type))
                {
                    type = _TypeReplaceDict[type];
                }

                if (willBeNullTypes.Contains(type) && CBIsNullable.Checked)
                {
                    type += "?";
                }

                if (type == "object")
                {
                    type = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ps[1]);
                }
                else if (type == "List<object>")
                {
                    type = $"List<{CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ps[1])}>";
                }

                sb.AppendLine($@"
                    /// <summary>
                    /// {(ps.Length > 3 ? ps[3] : "")}
                    /// </summary>
                    public {type} {ps[1]} {{get;set;}}");
            }

            sb.Append("}");

            TBResult.Text = sb.ToString();
        }

        /// <summary>
        /// 方案四：0.参数名、1.是否必须、2.类型、3.说明
        /// </summary>
        private void Button4_Click(object sender, EventArgs e)
        {
            var strs = TBContent.Text.Replace("\r\n", "\r").Split('\r').ToList();
            StringBuilder sb = new StringBuilder();
            List<string> willBeNullTypes = new List<string>() { "DateTime", "bool", "decimal", "int" };
            Dictionary<string, string> dict = new Dictionary<string, string>() { { "date", "DateTime" }, { "datetime", "DateTime" }, { "String", "string" }, };
            List<string> needRemoveList = new List<string>() { "│ ├ ", "│ ├", "\r\n", };

            sb.AppendLine($"public class MyClass {Environment.NewLine}{{");

            strs.RemoveAll(x => needRemoveList.Contains(x));

            string remain = "";
            foreach (var str in strs)
            {
                string line = str;
                if (!string.IsNullOrEmpty(remain))
                {
                    line = $"{remain} {line}";
                    remain = "";
                }

                if (string.IsNullOrEmpty(line))
                    continue;

                foreach (string s in needRemoveList)
                {
                    line = line.Replace(s, "");
                }

                line = line.Replace(" ", "\t");
                var ps = line.Split('\t');

                string propName = ps[0];
                if (ps.Length == 1 || line.EndsWith("\t"))
                {
                    if (propName == "" || needRemoveList.Contains(propName))
                    {
                        remain = "";
                    }
                    else
                    {
                        remain = propName;
                    }

                    continue;
                }

                string type = ps[2];
                if (dict.ContainsKey(type))
                {
                    type = dict[type];
                }

                if (willBeNullTypes.Contains(type) && CBIsNullable.Checked)
                {
                    type += "?";
                }

                sb.AppendLine($@"
                    /// <summary>
                    /// [{ps[1]}] {(ps.Length > 3 ? ps[3] : "")}
                    /// </summary>
                    public {type} {ps[0]} {{get;set;}}");
            }

            sb.Append("}");

            TBResult.Text = sb.ToString();
        }

        /// <summary>
        /// 方案五：0.参数名、1.类型、2.说明
        /// </summary>
        private void Button5_Click(object sender, EventArgs e)
        {
            var strs = TBContent.Text.Replace("\r\n", "\r").Split('\r');
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"public class MyClass {Environment.NewLine}{{");

            foreach (var str in strs)
            {
                if (string.IsNullOrEmpty(str))
                    continue;

                var ps = str.Split('\t');

                if (ps[0] == "参数名")
                    continue;

                string type = ps[1];
                if (_TypeReplaceDict.ContainsKey(type))
                {
                    type = _TypeReplaceDict[type];
                }

                if (_WillBeNullTypes.Contains(type) && CBIsNullable.Checked)
                {
                    type += "?";
                }

                if (type == "object")
                {
                    type = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ps[1]);
                }
                else if (type == "List<object>")
                {
                    type = $"List<{CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ps[1])}>";
                }

                sb.AppendLine($@"
                    /// <summary>
                    /// {(ps.Length > 2 ? ps[2] : "")}
                    /// </summary>
                    public {type} {ps[0]} {{ get; set; }}");
            }

            sb.Append("}");

            TBResult.Text = sb.ToString();
        }

        /// <summary>
        /// 方案六：0.名称、1.类型、2.是否必须、3.示例值、4.更多限制、5.描述
        /// </summary>
        private void Button6_Click(object sender, EventArgs e)
        {
            var strs = TBContent.Text.Replace("\r\n", "\r").Split('\r');
            StringBuilder sb = new StringBuilder();

            //sb.AppendLine($"public class MyClass {Environment.NewLine}{{");

            foreach (var str in strs)
            {
                if (string.IsNullOrEmpty(str))
                    continue;

                var ps = str.Split('\t');

                string propName = ps[0];
                if (propName == "名称")
                {
                    continue;
                }

                string type = ps[1];
                if (_TypeReplaceDict.ContainsKey(type))
                {
                    type = _TypeReplaceDict[type];
                }

                if (_WillBeNullTypes.Contains(type) && CBIsNullable.Checked)
                {
                    type += "?";
                }

                sb.AppendLine($@"
                /// <summary>
                /// [{ps[2]}] {(ps.Length > 3 ? $"{ps[5]} | 示例值：{ps[3]} | 更多限制：{ps[4]}" : "")}
                /// </summary>
                public {type} {propName} {{get;set;}}");
            }

            //sb.Append("}");

            TBResult.Text = sb.ToString();
        }

        /// <summary>
        /// 方案七（XML=>C#）
        /// </summary>
        private void Button7_Click(object sender, EventArgs e)
        {
            try
            {
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(TBContent.Text);

                XmlElement root = xdoc.DocumentElement;
                string rootName = root.Name;

                var nodes = root.ChildNodes;

                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"public class {rootName} {Environment.NewLine}{{");

                foreach (XmlElement node in nodes)
                {
                    string propName = node.Name;

                    string type = "string";
                    if (_TypeReplaceDict.ContainsKey(type))
                    {
                        type = _TypeReplaceDict[type];
                    }

                    if (_WillBeNullTypes.Contains(type) && CBIsNullable.Checked)
                    {
                        type += "?";
                    }

                    sb.AppendLine($@"
                    /// <summary>
                    /// {node.InnerText}
                    /// </summary>
                    public {type} {propName} {{get;set;}}");
                }

                sb.Append("}");

                TBResult.Text = sb.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex}");
            }
        }

        /// <summary>
        /// 方案八：0.参数名、1.类型、2.说明、3.描述
        /// </summary>
        private void button8_Click(object sender, EventArgs e)
        {
            var strs = TBContent.Text.Replace("\r\n", "\r").Split('\r');
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"public class MyClass {Environment.NewLine}{{");

            foreach (var str in strs)
            {
                if (string.IsNullOrEmpty(str))
                    continue;

                var ps = str.Split('\t');

                if (ps[0] == "参数名")
                    continue;

                string type = ps[1];
                if (_TypeReplaceDict.ContainsKey(type))
                {
                    type = _TypeReplaceDict[type];
                }

                if (_WillBeNullTypes.Contains(type) && CBIsNullable.Checked)
                {
                    type += "?";
                }

                if (type == "object")
                {
                    type = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ps[1]);
                }
                else if (type == "List<object>")
                {
                    type = $"List<{CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ps[1])}>";
                }

                sb.AppendLine($@"
                    /// <summary>
                    /// {(ps.Length > 2 ? ps[2] : "")}{(ps.Length > 3 && !string.IsNullOrWhiteSpace(ps[3]) ? "（" + ps[3] + "）" : "")}
                    /// </summary>
                    public {type} {ps[0]} {{ get; set; }}");
            }

            sb.Append("}");

            TBResult.Text = sb.ToString();
        }
    }
}
